% remove trend and bias from time series
% normalizes if requested
% latest date 11.12.2002
% usage [data] = CorTre(data,flag)
% known bug - length of data should be even
% Ref: ProcMT manual
%26JULY06 incorporated changes to handle NaN's

function[data] = CorTre(data,flag),

	block = length(data);
	bias  = nanmean(data);
	P2 = nansum(data(1:block/2));
	P1 = nansum(data(1+block/2:block));
	trend = 4*(P1-P2)/(block*block);

	for n=1:block,
	data(n) = data(n) - bias + (block/2 - n - 0.5 )*trend;
		 % changed according to pmttscom.mod on 17.11.2001
	end;


	if flag == 1,
	MI = nanmin(data);
	MA = nanmax(data);
	for n=1:block,
		data(n) = (data(n) - MI)/(MA - MI);
		end;
	end;

